﻿namespace Proto.Fields
{
    using System;
    using System.Reflection;

    public class Get<T> where T : IColumnCompatible
    {
        private static readonly T FAIL;
        static Get()
        {
            FieldInfo fail_field = typeof(T).GetField("FAIL");
            if( fail_field != null )
            {
                FAIL = (T) fail_field.GetValue( typeof( T ));
            }
            else
            {
                FAIL = default(T);
            }
        }

        public T this[IKey key, params IProvider<T>[] providers]
        {
            get
            {
                return this[ key, null, providers];
            }
        }

        public T this[ IKey key, 
                       Predicate<T> skip_check, 
                       params IProvider<T>[] providers]
        {
            get
            {
                T best_guess = FAIL;

                foreach( IProvider<T> provider in providers )
                {
                    T qty = provider.Get(key);
                    if( skip_check != null && skip_check( qty ) )
                    {
                        return qty;
                    }
                   
                }
                return best_guess;
            }
        }
    }
}